#include "mutil.h"

#include <QMessageBox>
#include <QResource>
#include <QFile>
#include <algorithm>
#include <stdio.h>

typedef std::map<QString, QString> Dictionary;
static Dictionary str_map;

void MUtil::debug(QString msg)
{
    QMessageBox::information(
                NULL,
                str_map.count("debug")
                    ? str_map["debug"]
                    : "debug",
                msg
                );
}

void MUtil::debugAndExit(QString msg)
{
    debug(msg);
    exit(EXIT_FAILURE);
}
void MUtil::loadStr()
{
    str_map.clear();

    QFile fo("../res/language.txt");
    fo.open(QFile::ReadOnly);

    while (!fo.atEnd())
    {
        QString s(fo.readLine());
        while (*(s.end() - 1) == '\n' || *(s.end() - 1) == ' ')
            s.remove(s.length() - 1, 1);
        auto p = std::find(s.begin(), s.end(), '=');
        QString s1(s.begin(), p - s.begin());
        ++p;
        QString s2(p, s.end() - p - 1);
        str_map[s1] = s2;
    }

    // read

    fo.close();
}

QString MUtil::getStr(QString id)
{
    if (!str_map.count(id))
        debugAndExit("Language symbol <" + id + "> not found.");
    return str_map.at(id);
}
